<template>
  <el-card class="box-card">
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
            <!-- 查询用户名框和重置按钮 -->
            <div style="display: flex; align-items: center;">
              <el-autocomplete
                v-model="state"
                :fetch-suggestions="querySearchUser"
                placeholder="请输入查询用户名称"
                @select="handleSelect"
              >
                <template slot="dropdown-item" slot-scope="{ item }">
                  <div>{{ item.realName }}</div>
                </template>
              </el-autocomplete>
              <el-button size="small" type="primary" @click="resetSearch">重置</el-button>
            </div>
            <div style="margin-left: auto;">
              <el-button size="small" type="primary" @click="showAdd">添加用户</el-button>
            </div>
            <!-- 用户列表 -->
            <div>
              <div v-for="user in userList" :key="user.id">
                {{ user.name }}
              </div>
            </div>
          </div>
          <!-- 这个表单会根据data的值动态生成内容 -->
          <el-table ref="userTable" :data="userList" style="width: 100%">
            <el-table-column type="selection" />
            <el-table-column type="index" label="序号" />
            <!--            <el-table-column label="头像" prop="userrole.img" width="80">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-image style="width: 30px; height: 30px" :src="scope.row.userrole.img" fit="cover" class="img-circle" />-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column label="性别" prop="userrole.gender" width="80">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ getGenderLabel(scope.row.userrole.gender) }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="权限" prop="role">
              <template v-slot="scope">
                <span v-if="scope.row.role === '1'">管理员</span>
                <span v-else>普通用户</span>
              </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="真实姓名" prop="realName" />
            <!--            <el-table-column label="工号" prop="userrole.jnumber" width="240" />-->
            <!--            <el-table-column label="邮箱" prop="email" width="240" />-->
            <!--            <el-table-column label="电话" prop="userrole.phone" width="240" />-->
            <!--            <el-table-column label="创建日期" prop="formatted_date_joined" width="240" />-->
            <!-- 其他列 -->
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <div style="display: flex; justify-content: space-around;">
                  <el-button size="mini" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="mini" type="warning" @click="confirmResetPassword(row.id)">重置密码</el-button>
                  <el-button
                    v-if="row.username !== 'admin'"
                    size="mini"
                    type="danger"
                    @click="confirmRemove(row.id)"
                  >删除</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- 隐藏的用户ID列 -->
            <el-table-column v-if="false" label="用户ID" prop="id" width="0" />
          </el-table>
          <el-pagination
            :current-page="query.pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            background="True"
            :total="query.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 确认重置密码对话框 -->
    <el-dialog :visible.sync="resetPasswordDialogVisible" title="确认重置密码">
      <span>确定要重置该用户的密码吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="resetPassword(confirmRow.id)">确定</el-button>
      </span>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog :visible.sync="removeDialogVisible" title="确认删除用户">
      <span>确定要删除该用户吗？此操作不可恢复。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="remove(confirmRow.id)">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加新用户" :visible.sync="showAddModal" width="50%" top="20px" append-to-body>
      <!-- 模态窗口的内容 -->
      <div class="modal-body">
        <el-form ref="form" :model="userInfo" :rules="rules" novalidate>
          <div class="row">
            <div class="col-xs-12">
              <!-- 隐藏列ID -->
              <!--              <el-form-item label="用户ID">-->
              <!--                <el-input v-if="false" v-model="userInfo.userId" />-->
              <!--              </el-form-item>-->
              <!-- 真实姓名 -->
              <el-form-item prop="username" label="用户名">
                <el-input v-model="userInfo.username" placeholder="请输入用户名" />
              </el-form-item>
              <el-form-item prop="realName" label="真实姓名">
                <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" />
              </el-form-item>

              <!-- 邮箱 -->
              <!--              <el-form-item label="邮箱">-->
              <!--                <el-input v-model="userInfo.email" placeholder="请输入邮箱" />-->
              <!--              </el-form-item>-->

              <!-- 电话 -->
              <!--              <el-form-item label="电话">-->
              <!--                <el-input v-model="userInfo.phone" placeholder="请输入电话" />-->
              <!--              </el-form-item>-->

              <!-- 电话 -->
              <!--              <el-form-item label="工号">-->
              <!--                <el-input v-model="userInfo.jnumber" placeholder="请输入个人工号" />-->
              <!--              </el-form-item>-->

              <!-- 密码 -->
              <el-form-item prop="password" label="密码">
                <el-input v-model="userInfo.password" type="password" placeholder="请输入密码" />
              </el-form-item>

              <!-- 确认密码 -->
              <el-form-item prop="confirmPassword" label="确认密码">
                <el-input v-model="userInfo.confirmPassword" type="password" placeholder="请确认密码" />
              </el-form-item>

              <el-form-item label="是否为管理员">
                <el-radio-group v-model="userInfo.role">-->
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 头像选择 -->
              <!--              <el-form-item label="头像">-->
              <!--                <el-radio-group v-model="userInfo.img">-->
              <!--                  <el-radio v-for="avatar in avatars" :key="avatar" :label="avatar">-->
              <!--                    <img :src="avatar" class="img-picker img64">-->
              <!--                  </el-radio>-->
              <!--                </el-radio-group>-->
              <!--              </el-form-item>-->

              <!-- 性别选择 -->
              <!--              <el-form-item label="性别">-->
              <!--                <el-radio-group v-model="userInfo.gender">-->
              <!--                  <el-radio :label="1">男</el-radio>-->
              <!--                  <el-radio :label="0">女</el-radio>-->
              <!--                </el-radio-group>-->
              <!--              </el-form-item>-->
            </div>
          </div>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddModal = false">取消</el-button>
        <el-button type="primary" @click="submitFormCreateUser">确认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户信息" :visible.sync="showEditModal" width="50%" top="20px" append-to-body>
      <!-- 模态窗口的内容 -->
      <div class="modal-body">
        <el-form ref="form" :model="userInfo" :rules="simpleRules" novalidate>
          <div class="row">
            <div class="col-xs-12">
              <!-- 真实姓名 -->
              <el-form-item prop="realName" label="真实姓名">
                <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input v-model="userInfo.password" type="password" placeholder="请输入密码" />
              </el-form-item>

              <!-- 确认密码 -->
              <el-form-item prop="confirmPassword" label="确认密码">
                <el-input v-model="userInfo.confirmPassword" type="password" placeholder="请确认密码" />
              </el-form-item>

              <el-form-item prop="role" label="是否为管理员">
                <el-radio-group v-model="userInfo.role">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 邮箱 -->
              <!--              <el-form-item label="邮箱">-->
              <!--                <el-input v-model="userInfo.email" placeholder="请输入邮箱" />-->
              <!--              </el-form-item>-->

              <!-- 电话 -->
              <!--              <el-form-item label="电话">-->
              <!--                <el-input v-model="userInfo.phone" placeholder="请输入电话" />-->
              <!--              </el-form-item>-->

              <!-- 电话 -->
              <!--              <el-form-item label="工号">-->
              <!--                <el-input v-model="userInfo.jnumber" placeholder="请输入个人工号" />-->
              <!--              </el-form-item>-->

              <!-- 密码 -->
              <!-- <el-form-item label="密码">-->
              <!--                <el-input v-model="userInfo.password" type="password" placeholder="请输入密码" />-->
              <!--              </el-form-item>-->

              <!-- 确认密码 -->
              <!--              <el-form-item label="确认密码">-->
              <!--                <el-input v-model="userInfo.confirmPassword" type="password" placeholder="请确认密码" />-->
              <!--              </el-form-item>-->

              <!-- 头像选择 -->
              <!--              <el-form-item label="头像">-->
              <!--                <el-radio-group v-model="userInfo.img">-->
              <!--                  <el-radio v-for="avatar in avatars" :key="avatar" :label="avatar">-->
              <!--                    <img :src="avatar" class="img-picker img64">-->
              <!--                  </el-radio>-->
              <!--                </el-radio-group>-->
              <!--              </el-form-item>-->

              <!-- 性别选择 -->
              <!--              <el-form-item label="性别">-->
              <!--                <el-radio-group v-model="userInfo.gender">-->
              <!--                  <el-radio :label="1">男</el-radio>-->
              <!--                  <el-radio :label="0">女</el-radio>-->
              <!--                </el-radio-group>-->
              <!--              </el-form-item>-->
            </div>
          </div>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditModal = false">取消</el-button>
        <el-button type="primary" @click="submitFormEditUser">确认</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getUserList,
  addUser,
  getUser,
  resetPasswd,
  deleteUser,
  editUser
} from '@/api/user'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      state: null,
      showAddModal: false,
      showEditModal: false,
      passwordConfirm: null,
      userInfo: {
        id: '',
        role: '',
        username: '',
        realName: '',
        password: '',
        confirmPassword: ''

      },
      resetPasswordDialogVisible: false,
      removeDialogVisible: false,
      confirmRow: {},
      rules: {
        // 对应用户名输入框的校验规则
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择是否为管理员', trigger: 'change' }
        ]
        // 可以在这里添加其他字段的校验规则
      },
      simpleRules: {
        realName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择是否为管理员', trigger: 'change' }
        ]
      },
      // avatars: ['avatar1.png', 'avatar2.png', 'avatar3.png', 'avatar4.png'], // 请根据实际情况替换
      userList: [], // 数据列表
      query: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  created() {
    this.fetchUserList()
  },
  methods: {
    confirmRemove(id) {
      this.confirmRow = id
      // this.removeDialogVisible = true
      this.$confirm('是否确认该操作', '提示', {
        iconClass: 'el-icon-question', // 自定义图标样式
        confirmButtonText: '确认', // 确认按钮文字更换
        cancelButtonText: '取消', // 取消按钮文字更换
        showClose: true, // 是否显示右上角关闭按钮
        type: 'warning' // 提示类型  success/info/warning/error
      }).then(() => {
        // 确认操作
        this.remove(id)
      }).catch(() => {
        // 取消操作
      })
    },
    confirmResetPassword(id) {
      // this.confirmRow = row
      // this.resetPasswordDialogVisible = true
      this.$confirm('是否确认该操作', '提示', {
        iconClass: 'el-icon-question', // 自定义图标样式
        confirmButtonText: '确认', // 确认按钮文字更换
        cancelButtonText: '取消', // 取消按钮文字更换
        showClose: true, // 是否显示右上角关闭按钮
        type: 'warning' // 提示类型  success/info/warning/error
      }).then(() => {
        // 确认操作
        this.resetPassword(id)
      }).catch(() => {
        // 取消操作
      })
    },
    resetSearch() {
      // 清空搜索框
      this.state = ''
      // 重新返回所有用户
      this.fetchUserList()
    },
    getGenderLabel(gender) {
      return gender === 1 ? '男' : '女'
    },
    showAdd() {
      this.userInfo = {
        realName: '',
        // email: '',
        password: '',
        confirmPassword: ''
        // img: '',
        // jnumber: '',
        // phone: '',
        // gender: null
      }
      this.showAddModal = true
    },
    submitFormEditUser() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 如果表单校验成功
          console.log('表单数据', this.userInfo)
          if (this.userInfo.password === undefined || this.userInfo.password === null) {
            this.userInfo.password = ''
            this.editUser()
            return
          } else if (this.userInfo.password.length < 6) {
            Message({
              message: '密码不能小于6位数',
              type: 'error',
              duration: 3000
            })
            return
          }
          this.editUser()

          this.showEditModal = false
        } else {
          // 如果表单校验失败
          console.error('表单校验失败')
          return false
        }
      })
    },
    querySearchUser(queryString, callback) {
      if (!queryString) {
        const allUsers = this.userList.map(user => ({ value: user.username }))
        callback(allUsers)
      } else {
        this.getUsersSuggestions(queryString).then(suggestions => {
          callback(suggestions)
        })
      }
    },
    getUsersSuggestions(queryString) {
      return new Promise(resolve => {
        const filteredSuggestions = this.userList.filter(user =>
          user.username.toLowerCase().includes(queryString.toLowerCase())
        )
        const suggestions = filteredSuggestions.map(user => ({ value: user.username }))
        resolve(suggestions)
      })
    },
    async handleSelect(item) {
      this.$set(this.userInfo, 'username', item.value)
      await this.fetchUserList(this.userInfo)
      console.log(this.userList)

      this.$refs.userTable.clearSelection()
      this.$refs.userTable.setCurrentRow()
    },
    validateConfirmPassword(rule, value, callback) {
      if (value === undefined) {
        value = null
      }
      if (value !== this.userInfo.password) {
        callback(new Error('确认密码和密码不匹配'))
      } else {
        callback()
      }
    },
    submitFormCreateUser() {
      if (this.userInfo.password.length < 6) {
        Message({
          message: '密码不能小于6位数',
          type: 'error',
          duration: 3000
        })
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('表单验证成功，提交表单')
          this.createUser()
        } else {
          console.error('表单验证失败')
          return false
        }
      })
    },
    createUser() {
      // if (!this.passwordMatch) {
      //   Message.error('密码和确认密码不匹配')
      //   return
      // }
      // 添加用户的逻辑
      if (this.userInfo.realName) {
        addUser(this.userInfo)
          .then(response => {
            // API 请求成功，显示成功消息
            if (response.status === 200) {
              Message({
                message: '操作成功',
                type: 'success',
                duration: 3000
              })
            } else {
              Message({
                message: response.message,
                type: 'error',
                duration: 3000
              })
              return
            }
            this.fetchUserList()
          }).catch(error => {
            // 处理错误情况
            console.log(error)
            Message.error('操作失败')
          })
      }
      this.showAddModal = false // 关闭模态窗口
    },
    editUser() {
      // if (this.userInfo.password === '') {
      //   this.userInfo.password = ''
      //   editUser_realName({ id: this.userInfo.id, realName: this.userInfo.realName })
      //     .then(response => {
      //       if (response.status === 200) {
      //         Message({
      //           message: '操作成功',
      //           type: 'success',
      //           duration: 3000
      //         })
      //       } else {
      //         Message({
      //           message: response.message,
      //           type: 'error',
      //           duration: 3000
      //         })
      //         return
      //       }
      //       this.fetchUserList()
      //     }).catch(error => {
      //       // 处理错误情况
      //       console.log(error)
      //       Message.error('操作失败')
      //     })
      // } else {
      //   if (this.userInfo.realName === '') {
      //     this.userInfo.realName = ''
      //     editUser_password({ id: this.userInfo.id, password: this.userInfo.password })
      //       .then(response => {
      //         if (response.status === 200) {
      //           Message({
      //             message: '操作成功',
      //             type: 'success',
      //             duration: 3000
      //           })
      //         } else {
      //           Message({
      //             message: response.message,
      //             type: 'error',
      //             duration: 3000
      //           })
      //           return
      //         }
      //         this.fetchUserList()
      //       }).catch(error => {
      //         // 处理错误情况
      //         console.log(error)
      //         Message.error('操作失败')
      //       })
      //   } else {
      editUser(this.userInfo)
        .then(response => {
          if (response.status === 200) {
            Message({
              message: '操作成功',
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
          this.fetchUserList()
        }).catch(error => {
          // 处理错误情况
          console.log(error)
          Message.error('操作失败')
        })
      // }
      // }
      this.showEditModal = false // 关闭模态窗口
    },
    showEdit(userId) {
      console.log('id:' + userId)
      // 编辑用户的逻辑
      this.getUser(userId)
      this.userInfo.id = userId
      this.showEditModal = true
    },
    resetPassword(userId) {
      resetPasswd(userId)
        .then(response => {
          if (response.status === 200) {
            Message({
              message: '重置密码成功！',
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
        }).catch(error => {
          // 处理错误情况
          console.log(error)
          Message.error('重置失败！')
        })
    },
    remove(userId) {
      console.log(userId)
      deleteUser(userId)
        .then(response => {
          if (response.status === 200) {
            Message({
              message: '删除用户成功！',
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
          this.fetchUserList()
        }).catch(error => {
          // 处理错误情况
          console.log(error)
          Message.error('删除失败！')
        })
    },
    handleSizeChange(newSize) {
      this.query.pageSize = newSize
      this.fetchUserList()
    },
    handleCurrentChange(newPage) {
      this.query.pageNum = newPage
      this.fetchUserList()
    },
    async fetchUserList(userInfo) {
      try {
        const queryParams = {
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize
        }
        console.log(userInfo)
        console.log(queryParams)
        const response = await getUserList(userInfo, queryParams)
        if (response.status === 200) {
          this.userList = response.pageInfo.list
          if (response.pageInfo.pageNum && response.pageInfo.pageSize && response.pageInfo.total) {
            this.query.pageNum = response.pageInfo.pageNum
            this.query.pageSize = response.pageInfo.pageSize
            this.query.total = response.pageInfo.total
          } else {
            this.query.pageNum = 1
            this.query.pageSize = 10
            this.total = 0
          }
        } else {
          Message({
            message: response.message,
            type: 'error',
            duration: 3000
          })
          return
        }
      } catch (error) {
        console.error('获取用户列表失败：', error)
        throw error
      }
    },
    async getUser(userId) {
      try {
        const response = await getUser(userId)
        this.userInfo = response.data
      } catch (error) {
        console.error('获取用户失败：', error)
        throw error
      }
    }
  }
}
</script>

<style scoped>
/* 自定义表格列的间距和样式 */
.el-table__body-wrapper {
  overflow: auto;
}

.el-table__body {
  padding: 10px;
  /* 调整表格内部的内边距 */
}

.el-table th,
.el-table td {
  padding: 10px;
  /* 调整表头和表格单元格的内边距 */
}

/* 您可以根据需要自定义更多的样式 */
</style>
